package me.siphone.fragment;

import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import androidx.swiperefreshlayout.widget.SwipeRefreshLayout;
import com.hjq.http.EasyHttp;
import com.hjq.http.listener.HttpCallbackProxy;
import java.util.List;
import me.siphone.Constants;
import me.siphone.adapter.CallHistoryAdapter;
import me.siphone.http.api.QueryCallHistoryApi;
import me.siphone.http.model.HttpData;
import org.linphone.R;

public class CallHistoryFragment extends BaseFragment {

    private SwipeRefreshLayout refresher;
    private RecyclerView rvCallHistory;
    private CallHistoryAdapter adapter;
    private int page = 1, size = 50;

    @Nullable
    @Override
    public View onCreateView(
            @NonNull LayoutInflater inflater,
            @Nullable ViewGroup container,
            @Nullable Bundle savedInstanceState) {

        View view = inflater.inflate(R.layout.fragment_call_history, container, false);
        rvCallHistory = view.findViewById(R.id.rv_call_history);
        rvCallHistory.setLayoutManager(new LinearLayoutManager(getContext()));

        refresher = view.findViewById(R.id.srl_call_history);
        refresher.setOnRefreshListener(
                new SwipeRefreshLayout.OnRefreshListener() {
                    @Override
                    public void onRefresh() {
                        page = 1;
                        refresher.setRefreshing(true);
                        queryCallHistory(page, size, false);
                    }
                });

        rvCallHistory.addOnScrollListener(
                new RecyclerView.OnScrollListener() {
                    @Override
                    public void onScrolled(@NonNull RecyclerView recyclerView, int dx, int dy) {
                        super.onScrolled(recyclerView, dx, dy);

                        if (dy <= 0) return; // 只关心向下滚动
                        LinearLayoutManager layoutManager =
                                (LinearLayoutManager) rvCallHistory.getLayoutManager();
                        int lastVisibleItem = layoutManager.findLastVisibleItemPosition();
                        int totalItemCount = layoutManager.getItemCount();

                        if (lastVisibleItem >= totalItemCount - 2) {
                            // 快要滑到底了，触发加载更多
                            queryCallHistory(++page, size, true);
                        }
                    }
                });

        queryCallHistory(page, size, false);

        return view;
    }

    private void queryCallHistory(int page, int size, boolean loadMore) {
        EasyHttp.get(this)
                .api(new QueryCallHistoryApi(page, size))
                .request(
                        new HttpCallbackProxy<HttpData<List<QueryCallHistoryApi.CallHistory>>>(
                                this) {
                            @Override
                            public void onHttpSuccess(
                                    @NonNull
                                            HttpData<List<QueryCallHistoryApi.CallHistory>>
                                                    result) {
                                super.onHttpSuccess(result);

                                if (loadMore) {
                                    adapter.addAll(result.getRows());
                                } else {
                                    refresher.setRefreshing(false);
                                    adapter = new CallHistoryAdapter(result.getRows());
                                    adapter.setListener(
                                            new CallHistoryAdapter.OnReplyClickListener() {
                                                @Override
                                                public void onReplyClick(
                                                        QueryCallHistoryApi.CallHistory
                                                                callHistory) {
                                                    AnswerFragment answerFragment =
                                                            new AnswerFragment();
                                                    Bundle data = new Bundle();
                                                    data.putInt(Constants.CALL_TYPE, 0);
                                                    data.putString(
                                                            Constants.CALL_ID,
                                                            callHistory.getCallId());
                                                    data.putString(
                                                            Constants.CALL_CONTENT,
                                                            callHistory.getRecordContent());
                                                    data.putBoolean(Constants.CALL_HISTORY, true);
                                                    answerFragment.setArguments(data);

                                                    getFragmentManager()
                                                            .beginTransaction()
                                                            .replace(
                                                                    R.id.fl_container,
                                                                    answerFragment)
                                                            .addToBackStack(
                                                                    answerFragment
                                                                            .getClass()
                                                                            .getSimpleName())
                                                            .commit();
                                                }
                                            });
                                    rvCallHistory.setAdapter(adapter);
                                }
                            }

                            @Override
                            public void onHttpFail(@NonNull Throwable throwable) {
                                super.onHttpFail(throwable);
                            }
                        });
    }
}
